package etnorservice.etnor_service.service.impl;
import etnorservice.etnor_service.config.FileUploadConfig;
import etnorservice.etnor_service.service.ImageUploadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.Set;
import java.util.UUID;
/**
 * Created with IntelliJ IDEA.
 *
 * @Author: cc
 * @Date: 2025/03/19/12:10
 **/
@Slf4j
@Service
@Primary
public class ServerImageUploadService implements ImageUploadService {

    private final FileUploadConfig config;

    public ServerImageUploadService(FileUploadConfig config) {
        this.config = config;
    }

    @Override
    public String uploadImage(MultipartFile file) throws IOException {
        validateImage(file);

        String fileName = generateFileName(file);
        Path uploadPath = getUploadPath();
        Path filePath = uploadPath.resolve(fileName);

        try {
            // 确保目录存在
            Files.createDirectories(filePath.getParent());

            // 保存文件
            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

            // 设置文件权限
            setFilePermissions(filePath);

            log.info("图片已上传到服务器: {}", filePath);
            return "/images/" + fileName;
        } catch (IOException e) {
            log.error("上传图片到服务器失败: {}", e.getMessage());
            throw new IOException("无法上传图片: " + fileName, e);
        }
    }

    @Override
    public void deleteImage(String imagePath) throws IOException {
        if (StringUtils.isEmpty(imagePath)) {
            return;
        }

        String fileName = imagePath.substring(imagePath.lastIndexOf('/') + 1);
        Path filePath = getUploadPath().resolve(fileName);

        try {
            Files.deleteIfExists(filePath);
            log.info("已从服务器删除图片: {}", filePath);
        } catch (IOException e) {
            log.error("从服务器删除图片失败: {}", e.getMessage());
            throw new IOException("无法删除图片: " + fileName, e);
        }
    }

    @Override
    public boolean exists(String imagePath) throws IOException {
        if (StringUtils.isEmpty(imagePath)) {
            return false;
        }

        String fileName = imagePath.substring(imagePath.lastIndexOf('/') + 1);
        Path filePath = getUploadPath().resolve(fileName);
        return Files.exists(filePath);
    }

    private void validateImage(MultipartFile file) {
        if (file.isEmpty()) {
            throw new IllegalArgumentException("请选择图片");
        }

        if (file.getSize() > config.getMaxFileSize()) {
            throw new IllegalArgumentException(
                    String.format("图片大小不能超过%dMB", config.getMaxFileSize() / 1024 / 1024));
        }

        String contentType = file.getContentType();
        if (!config.getAllowedTypes().contains(contentType)) {
            throw new IllegalArgumentException("不支持的图片格式: " + contentType);
        }
    }

    private String generateFileName(MultipartFile file) {
        String originalFileName = file.getOriginalFilename();
        String extension = originalFileName.substring(originalFileName.lastIndexOf("."));
        return UUID.randomUUID().toString() + extension;
    }

    private Path getUploadPath() throws IOException {
        Path uploadPath = Paths.get(config.getUploadDir()).toAbsolutePath().normalize();
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }
        return uploadPath;
    }

    private void setFilePermissions(Path filePath) throws IOException {
        try {
            Set<PosixFilePermission> permissions = PosixFilePermissions.fromString("rw-r--r--");
            Files.setPosixFilePermissions(filePath, permissions);
        } catch (UnsupportedOperationException e) {
            log.warn("当前文件系统不支持POSIX文件权限");
        }
    }
    @Override
    public Path getImagePath(String imageUrl) throws IOException {
        if (StringUtils.isEmpty(imageUrl)) {
            throw new IllegalArgumentException("图片URL不能为空");
        }
        String fileName = imageUrl.substring(imageUrl.lastIndexOf('/') + 1);
        return getUploadPath().resolve(fileName);
    }

}